package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.PerssionListAdapter1;
import com.github.postsanf.yinian.adapter.PerssionListAdapter2;
import com.github.postsanf.yinian.adapter.PerssionListAdapter3;
import com.github.postsanf.yinian.adapter.PerssionListAdapter4;
import com.github.postsanf.yinian.bean.YNPerssion;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.fragment.PeopleTimeLineFragment;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.widget.MySwipeMenuListView;
import com.github.postsanf.yinian.widget.SwipeMenu;
import com.github.postsanf.yinian.widget.SwipeMenuCreator;
import com.github.postsanf.yinian.widget.SwipeMenuItem;
import com.github.postsanf.yinian.widget.SwipeMenuListView;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class StealEachPerssionActivity extends BaseActivity implements View.OnClickListener {
    private int userId;
    private List<YNPerssion> ynPerssionList1 = new ArrayList<>();
    private List<YNPerssion> ynPerssionList2 = new ArrayList<>();
    private List<YNPerssion> ynPerssionList3 = new ArrayList<>();
    private List<YNPerssion> ynPerssionList4 = new ArrayList<>();
    private MySwipeMenuListView mySwipeMenuListView1;
    private MySwipeMenuListView mySwipeMenuListView2;
    private MySwipeMenuListView mySwipeMenuListView3;
    private MySwipeMenuListView mySwipeMenuListView4;
    private PerssionListAdapter1 perssionListAdapter1;
    private PerssionListAdapter2 perssionListAdapter2;
    private PerssionListAdapter3 perssionListAdapter3;
    private PerssionListAdapter4 perssionListAdapter4;
    private RelativeLayout rl_openeach, rl_writeyouopen, rl_toyouclose, rl_eachclose;
    private View rl_openeach_kong, rl_writeyouopen_kong, rl_toyouclose_kong, rl_eachclose_kong;
    private LinearLayout ll_stealeachperssion_empty;
    private ImageView stealeachperssion_emptyinvite;
    private ImageView iv_stealeachperssion_course;
    private ScrollView ll_stealeachperssion_scrov;
    private RelativeLayout stealeachperssion_guide;
    boolean bb1 = false;
    boolean bb2 = false;
    boolean bb3 = false;
    boolean bb4 = false;
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    perssionListAdapter1.notifyDataSetChanged();
                    if (ynPerssionList1.size() > 0) {
                        rl_openeach.setVisibility(View.VISIBLE);
                        rl_openeach_kong.setVisibility(View.VISIBLE);
                        if (!SpUtils.getBoolean(StealEachPerssionActivity.this, "stealperssion")) {
                            stealeachperssion_guide.setVisibility(View.VISIBLE);
                        }
                    } else {
                        rl_openeach.setVisibility(View.GONE);
                        rl_openeach_kong.setVisibility(View.GONE);
                    }
                    bb1 = true;
                    myHandler.sendEmptyMessage(5);
                    break;
                case 2:
                    perssionListAdapter2.notifyDataSetChanged();
                    if (ynPerssionList2.size() > 0) {
                        rl_writeyouopen.setVisibility(View.VISIBLE);
                        rl_writeyouopen_kong.setVisibility(View.VISIBLE);
                    } else {
                        rl_writeyouopen.setVisibility(View.GONE);
                        rl_writeyouopen_kong.setVisibility(View.GONE);
                    }
                    bb2 = true;
                    myHandler.sendEmptyMessage(5);
                    break;
                case 3:
                    perssionListAdapter3.notifyDataSetChanged();
                    if (ynPerssionList3.size() > 0) {
                        rl_toyouclose.setVisibility(View.VISIBLE);
                        rl_toyouclose_kong.setVisibility(View.VISIBLE);
                        if (!SpUtils.getBoolean(StealEachPerssionActivity.this, "stealperssion")) {
                            stealeachperssion_guide.setVisibility(View.VISIBLE);
                        }
                    } else {
                        rl_toyouclose.setVisibility(View.GONE);
                        rl_toyouclose_kong.setVisibility(View.GONE);
                    }
                    bb3 = true;
                    myHandler.sendEmptyMessage(5);
                    break;
                case 4:
                    perssionListAdapter4.notifyDataSetChanged();
                    if (ynPerssionList4.size() > 0) {
                        rl_eachclose.setVisibility(View.VISIBLE);
                        rl_eachclose_kong.setVisibility(View.VISIBLE);
                    } else {
                        rl_eachclose.setVisibility(View.GONE);
                        rl_eachclose_kong.setVisibility(View.GONE);
                    }
                    bb4 = true;
                    myHandler.sendEmptyMessage(5);
                    break;
                case 5:
                    if (bb1 && bb2 && bb3 && bb4) {
                        if (mProgressDialog != null)
                            mProgressDialog.dismiss();
                        bb1 = false;
                        bb2 = false;
                        bb3 = false;
                        bb4 = false;
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stealeachperssion);
        initView();
        registerBoradcastReceiver();
        if (Integer.parseInt(YNSingleton.getInstance().getCurAlbum().getGnum()) < 2) {
            ll_stealeachperssion_empty.setVisibility(View.VISIBLE);
            ll_stealeachperssion_scrov.setVisibility(View.GONE);
        } else {
            judgeDialog();
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionupdatePerssionList);
        myIntentFilter.addAction(ACTIONs.actionsharePerssionList);
        registerReceiver(mListReceiver, myIntentFilter);
    }

    private void initView() {
        userId = application.getCurID();
        findViewById(R.id.iv_back).setOnClickListener(this);
        stealeachperssion_guide = (RelativeLayout) findViewById(R.id.stealeachperssion_guide);
        stealeachperssion_guide.setOnClickListener(this);
        rl_openeach = (RelativeLayout) findViewById(R.id.rl_openeach);
        rl_openeach_kong = (View) findViewById(R.id.rl_openeach_kong);
        rl_writeyouopen = (RelativeLayout) findViewById(R.id.rl_writeyouopen);
        rl_writeyouopen_kong = (View) findViewById(R.id.rl_writeyouopen_kong);
        rl_toyouclose = (RelativeLayout) findViewById(R.id.rl_toyouclose);
        rl_toyouclose_kong = (View) findViewById(R.id.rl_toyouclose_kong);
        rl_eachclose = (RelativeLayout) findViewById(R.id.rl_eachclose);
        rl_eachclose_kong = (View) findViewById(R.id.rl_eachclose_kong);
        ll_stealeachperssion_empty = (LinearLayout) findViewById(R.id.ll_stealeachperssion_empty);
        ll_stealeachperssion_scrov = (ScrollView) findViewById(R.id.ll_stealeachperssion_scrov);
        stealeachperssion_emptyinvite = (ImageView) findViewById(R.id.stealeachperssion_emptyinvite);
        stealeachperssion_emptyinvite.setOnClickListener(this);
        findViewById(R.id.stealeachperssion_emptylookcourse).setOnClickListener(this);
        iv_stealeachperssion_course = (ImageView) findViewById(R.id.iv_stealeachperssion_course);
        iv_stealeachperssion_course.setOnClickListener(this);
        mySwipeMenuListView1 = (MySwipeMenuListView) findViewById(R.id.list1);
        mySwipeMenuListView2 = (MySwipeMenuListView) findViewById(R.id.list2);
        mySwipeMenuListView3 = (MySwipeMenuListView) findViewById(R.id.list3);
        mySwipeMenuListView4 = (MySwipeMenuListView) findViewById(R.id.list4);
        perssionListAdapter1 = new PerssionListAdapter1(StealEachPerssionActivity.this, ynPerssionList1, application.getCurGid());
        perssionListAdapter2 = new PerssionListAdapter2(StealEachPerssionActivity.this, ynPerssionList2, application.getCurID(), application.getCurGid());
        perssionListAdapter3 = new PerssionListAdapter3(StealEachPerssionActivity.this, ynPerssionList3);
        perssionListAdapter4 = new PerssionListAdapter4(StealEachPerssionActivity.this, ynPerssionList4, application.getCurID(), application.getCurGid());
        mySwipeMenuListView1.setAdapter(perssionListAdapter1);
        mySwipeMenuListView2.setAdapter(perssionListAdapter2);
        mySwipeMenuListView3.setAdapter(perssionListAdapter3);
        mySwipeMenuListView4.setAdapter(perssionListAdapter4);
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
                openItem.setBackground(new ColorDrawable(Color.rgb(250, 50,
                        50)));
                openItem.setWidth(UIHelper.dip2px(StealEachPerssionActivity.this, 102));
                openItem.setTitle("取消授权");
                openItem.setTitleSize(16);
                openItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(openItem);
            }
        };
        mySwipeMenuListView1.setMenuCreator(creator);
        mySwipeMenuListView1.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                cancelSinglePerssion(ynPerssionList1.get(position).getUserid());
                return false;
            }
        });
        mySwipeMenuListView3.setMenuCreator(creator);
        mySwipeMenuListView3.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                cancelSinglePerssion(ynPerssionList3.get(position).getUserid());
                return false;
            }
        });
    }

    private void cancelSinglePerssion(int beuserid) {
        String urlsto = getString(R.string.SLIVER_URL) + "AuthorizeOrCancelForWatchPhoto";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_BEUSER_ID, String.valueOf(beuserid));
        mParam.put(CommonConstants.YNS_TYPE, "cancel");
        Log.i("xjs", "cancelSinglePerssion+mParammParammParam==>" + mParam.toString());
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            Log.i("xjs", "cancelSinglePerssion==>" + s);
                            JSONObject result = new JSONObject(s);
                            if (result.optInt("code") == 0) {
                                initPerssionList();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.stealeachperssion_emptyinvite:
                Intent intent = new Intent(StealEachPerssionActivity.this, InviteChooseActivity.class);
                intent.putExtra(CommonConstants.YNDATAS, YNSingleton.getInstance().getCurAlbum());
                startActivity(intent);
                break;
            case R.id.stealeachperssion_emptylookcourse:
            case R.id.iv_stealeachperssion_course:
                Intent intent2 = new Intent(StealEachPerssionActivity.this, StealCourseVideoActivity.class);
                intent2.putExtra("fromPerssion", true);
                startActivity(intent2);
                break;
            case R.id.stealeachperssion_guide:
                stealeachperssion_guide.setVisibility(View.GONE);
                SpUtils.put(StealEachPerssionActivity.this, "stealperssion", true);
                break;
        }
    }

    private void judgeDialog() {
        boolean isPerssionGood = PeopleTimeLineFragment.isPerssionGood;
        Log.i("xjs", "isPerssionGood==>" + isPerssionGood);
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("groupid", String.valueOf(application.getCurGid()));
        String urlsto = getString(R.string.SLIVER_URL) + "GetGroupMemberAuthorizeList";
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "judgeDialogs===>" + s.toString());
                        try {
                            JSONObject result = new JSONObject(s);
                            if (result.optInt("code") == 0) {
                                JSONObject jsonObject = result.optJSONArray("data").optJSONObject(0);
                                JSONArray unilateralOfOthersList = jsonObject.optJSONArray("unilateralOfOthersList");
//                                JSONArray unilateralOfMeList = jsonObject.optJSONArray("unilateralOfMeList");
//                                JSONArray mutualAuthorizeList = jsonObject.optJSONArray("mutualAuthorizeList");
                                JSONArray mutualUnauthorizeList = jsonObject.optJSONArray("mutualUnauthorizeList");
//                                if (PeopleSpaceActivity2.isPerssionGood) {
                                if (unilateralOfOthersList.length() > 0 || mutualUnauthorizeList.length() > 0) {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(StealEachPerssionActivity.this).setMessage("你想跟这个圈子里现在的成员一起玩偷照片？")
                                            .setPositiveButton(R.string.yn_app_shide, new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int whichButton) {
                                                    if (!PeopleTimeLineFragment.isPerssionGood) {
                                                        showToast("你的本地照片总数少于3张，无法偷取别人的照片！");
                                                    } else {
                                                        AuthorizeAllPerssion();
                                                    }
                                                }
                                            })
                                            .setNegativeButton(R.string.yn_app_buxiangwan, new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int whichButton) {
                                                    initPerssionList();
                                                }
                                            });
                                    builder.setCancelable(false);
                                    builder.show();
                                } else {
                                    initPerssionList();
                                }
                            }
//                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void AuthorizeAllPerssion() {
        String urlsto = getString(R.string.SLIVER_URL) + "AuthorizeOrCancelForWatchPhoto";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        Log.i("xjs", "uuserid==>" + String.valueOf(application.getCurID()));
        Log.i("xjs", "groupid==>" + String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_TYPE, "authorizeAll");
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "AuthorizeAllPerssion==>" + s);
                        try {
                            JSONObject result = new JSONObject(s);
                            if (result.optInt("code") == 0) {
                                initPerssionList();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private ProgressDialog mProgressDialog;

    private void initPerssionList() {
        mProgressDialog = ProgressDialog.show(this, "", "");
        ynPerssionList1.clear();
        ynPerssionList2.clear();
        ynPerssionList3.clear();
        ynPerssionList4.clear();
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("groupid", String.valueOf(application.getCurGid()));
        Log.i("xjs", "userid===>" + application.getCurID());
        Log.i("xjs", "groupid===>" + application.getCurGid());
        String urlsto = getString(R.string.SLIVER_URL) + "GetGroupMemberAuthorizeList";
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "perssions===>" + s.toString());
                        try {
                            JSONObject result = new JSONObject(s);
                            if (result.optInt("code") == 0) {
                                JSONObject jsonObject = result.optJSONArray("data").optJSONObject(0);
                                //别人对我授权,我没有对他授权
                                JSONArray unilateralOfOthersList = jsonObject.optJSONArray("unilateralOfOthersList");
                                for (int i = 0; i < unilateralOfOthersList.length(); i++) {
                                    JSONObject eb = unilateralOfOthersList.optJSONObject(i);
                                    YNPerssion ynPerssion = new YNPerssion();
                                    ynPerssion.setUpic(eb.optString("upic"));
                                    ynPerssion.setUserid(eb.optInt("userid"));
                                    ynPerssion.setUnickname(eb.optString("unickname"));
                                    ynPerssionList2.add(ynPerssion);
                                }
                                JSONArray unilateralOfMeList = jsonObject.optJSONArray("unilateralOfMeList");
                                //我对别人授权,别人没有对我授权
                                for (int j = 0; j < unilateralOfMeList.length(); j++) {
                                    JSONObject eb = unilateralOfMeList.optJSONObject(j);
                                    YNPerssion ynPerssion = new YNPerssion();
                                    ynPerssion.setUpic(eb.optString("upic"));
                                    ynPerssion.setUserid(eb.optInt("userid"));
                                    ynPerssion.setUnickname(eb.optString("unickname"));
                                    ynPerssionList3.add(ynPerssion);
                                }
                                //互相已授权
                                JSONArray mutualAuthorizeList = jsonObject.optJSONArray("mutualAuthorizeList");
                                for (int k = 0; k < mutualAuthorizeList.length(); k++) {
                                    JSONObject eb = mutualAuthorizeList.optJSONObject(k);
                                    YNPerssion ynPerssion = new YNPerssion();
                                    ynPerssion.setUpic(eb.optString("upic"));
                                    ynPerssion.setIsMeSee(eb.optInt("isMeSee"));
                                    ynPerssion.setSeeNum(eb.optInt("seeNum"));
                                    ynPerssion.setUserid(eb.optInt("userid"));
                                    ynPerssion.setUnickname(eb.optString("unickname"));
                                    ynPerssionList1.add(ynPerssion);
                                }
                                //互相未授权
                                JSONArray mutualUnauthorizeList = jsonObject.optJSONArray("mutualUnauthorizeList");
                                for (int k = 0; k < mutualUnauthorizeList.length(); k++) {
                                    JSONObject eb = mutualUnauthorizeList.optJSONObject(k);
                                    YNPerssion ynPerssion = new YNPerssion();
                                    ynPerssion.setUpic(eb.optString("upic"));
                                    ynPerssion.setUserid(eb.optInt("userid"));
                                    ynPerssion.setUnickname(eb.optString("unickname"));
                                    ynPerssionList4.add(ynPerssion);
                                }
                                myHandler.sendEmptyMessage(1);
                                myHandler.sendEmptyMessage(2);
                                myHandler.sendEmptyMessage(3);
                                myHandler.sendEmptyMessage(4);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    BroadcastReceiver mListReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionsharePerssionList:
                    UMWeb web = new UMWeb("http://wx.zhuiyinanian.com/stealPicFromFriend");
                    web.setTitle("来和我玩互偷本地照片吧！");
                    web.setDescription("在和Ta的忆年圈子里，每天可以偷取三张对方的本地照片。");
                    new ShareAction(StealEachPerssionActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                            .withMedia(web)
                            .share();
                    break;
                case ACTIONs.actionupdatePerssionList:
                    initPerssionList();
                    break;
            }
        }
    };

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(StealEachPerssionActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(StealEachPerssionActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(StealEachPerssionActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                com.umeng.socialize.utils.Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(StealEachPerssionActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mListReceiver);
    }
}
